<template>
  <div class="activity-container">
    <!-- 搜索和筛选区域 -->
    <el-row :gutter="20" class="mb10">
      <el-col :span="6">
        <el-input
          v-model="queryParams.searchKey"
          placeholder="搜索活动名称"
          clearable
          @keyup.enter.native="getList"
        >
          <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="6">
        <el-select v-model="queryParams.type" placeholder="活动类型" clearable @change="getList">
          <el-option label="全部" value=""></el-option>
          <el-option label="考试" :value="1"></el-option>
          <el-option label="测评" :value="2"></el-option>
          <el-option label="作业" :value="3"></el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="queryParams.status" placeholder="活动状态" clearable @change="getList">
          <el-option label="全部" value=""></el-option>
          <el-option label="未开始" :value="1"></el-option>
          <el-option label="进行中" :value="2"></el-option>
          <el-option label="已结束" :value="3"></el-option>
        </el-select>
      </el-col>
    </el-row>

    <!-- 活动列表 -->
    <el-table :data="activityList" style="width: 100%">
      <el-table-column prop="title" label="名称">
        <template #default="{row}">
          <div class="activity-title">
            <el-tag :type="row.type | activityTypeFilter" size="mini">
              {{ row.type | activityTypeNameFilter }}
            </el-tag>
            <span>{{ row.title }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="400">
        <template #default="{row}">
          <el-tag :type="getActivityStatus(row) | statusTagTypeFilter" effect="dark">
            {{ getActivityStatus(row) | activityStatusFilter }}
          </el-tag>
          <div v-if="getActivityStatus(row) === 1" class="countdown">
            距离开考: {{ formatCountdown(row.startTime) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="300">
        <template #default="{row}">
          {{ row.startTime | formatDateTime }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="300">
        <template #default="{row}">
          {{ row.endTime | formatDateTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button type="text" @click="handleViewDetail(row)">详情</el-button>
          <el-button
            v-if="getActivityStatus(row) === 2"
            type="text"
            @click="handleStartActivity(row)">
            进入
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 活动详情对话框 -->
    <el-dialog
      :title="currentActivity.title"
      :visible.sync="detailDialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="activity-detail">
        <div class="detail-row">
          <span class="label">活动类型:</span>
          <el-tag :type="currentActivity.type | activityTypeFilter">
            {{ currentActivity.type | activityTypeNameFilter }}
          </el-tag>
        </div>
        <div class="detail-row">
          <span class="label">当前状态:</span>
          <el-tag :type="getActivityStatus(currentActivity) | statusTagTypeFilter">
            {{ getActivityStatus(currentActivity) | activityStatusFilter }}
          </el-tag>
          <span v-if="getActivityStatus(currentActivity) === 1" class="countdown">
            距离开考: {{ formatCountdown(currentActivity.startTime) }}
          </span>
        </div>
        <div class="detail-row">
          <span class="label">开始时间:</span>
          <span>{{ currentActivity.startTime | formatDateTime }}</span>
        </div>
        <div class="detail-row">
          <span class="label">结束时间:</span>
          <span>{{ currentActivity.endTime | formatDateTime }}</span>
        </div>
        <div v-if="currentActivity.type === 1" class="detail-row">
          <span class="label">考试时长:</span>
          <span>{{ currentActivity.timeLimit }} 分钟</span>
        </div>
        <div v-if="currentActivity.type === 1" class="detail-row">
          <span class="label">身份验证:</span>
          <span>{{ currentActivity.needIdentity ? '需要' : '不需要' }}</span>
        </div>
        <div class="detail-row">
          <span class="label">试卷总分:</span>
          <span>{{ currentActivity.paper.totalScore }} 分</span>
        </div>
        <div class="detail-row">
          <span class="label">及格分数:</span>
          <span>{{ currentActivity.paper.passScore || '--' }} 分</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
          v-if="getActivityStatus(currentActivity) === 2"
          type="primary"
          @click="handleStartActivity(currentActivity)">
          进入{{ currentActivity.type | activityTypeNameFilter }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 考试身份验证对话框 -->
    <el-dialog
      title="考试身份验证"
      :visible.sync="identityDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="identity-verify">
        <div class="verify-step" v-if="verifyStep === 1">
          <h3>第一步: 人脸识别</h3>
          <div class="camera-container">
            <video ref="video" autoplay playsinline class="camera-preview"></video>
            <canvas ref="canvas" class="camera-canvas"></canvas>
          </div>
          <div class="verify-tip">请确保面部清晰可见，光线充足</div>
          <el-button type="primary" @click="captureImage">拍照验证</el-button>
        </div>
        <div class="verify-step" v-else-if="verifyStep === 2">
          <h3>第二步: 信息确认</h3>
          <div class="verify-info">
            <div class="info-row">
              <span class="label">姓名:</span>
              <span>{{ userInfo.userName }}</span>
            </div>
            <div class="info-row">
              <span class="label">学号:</span>
              <span>{{ userInfo.studentId }}</span>
            </div>
            <div class="info-row">
              <span class="label">照片:</span>
              <img :src="capturedImage" class="verify-image">
            </div>
          </div>
          <div class="verify-actions">
            <el-button @click="retryCapture">重新拍照</el-button>
            <el-button type="primary" @click="confirmIdentity">确认信息</el-button>
          </div>
        </div>
        <div class="verify-step" v-else-if="verifyStep === 3">
          <h3>验证成功</h3>
          <div class="verify-success">
            <i class="el-icon-success"></i>
            <p>身份验证通过，即将进入考试...</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getActivityDetail, getExamDetail, getStudentActivities, verifyIdentity} from '@/api/exam/sudentGroupDetail'
import {getToken} from '@/utils/auth'
import {parseTime} from "@/utils/quiz"

export default {
  name: 'StudentActivityTab',
  props: {
    groupId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchKey: '',
        type: '',
        status: ''
      },
      activityList: [],
      total: 0,
      currentActivity: {
        title: '',
        type: 1,
        startTime: null,
        endTime: null,
        timeLimit: 0,
        needIdentity: false,
        paper: {
          totalScore: 0,
          passScore: null
        }
      },
      detailDialogVisible: false,
      identityDialogVisible: false,
      verifyStep: 1,
      userInfo: {
        userName: '张三',
        studentId: '20230001'
      },
      capturedImage: '',
      stream: null,
      countdownInterval: null
    }
  },
  created() {
    console.log('groupId======>', this.groupId);
    this.getList()
  },
  beforeDestroy() {
    this.stopCamera()
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval)
    }
  },
  methods: {
    getList() {
      // 模拟数据 - 实际项目中替换为API调用
      // this.activityList = this.mockLoadExamList()
      // this.total = this.activityList.length

      // 实际API调用
      getStudentActivities(this.groupId, this.queryParams).then(response => {
        this.activityList = response.rows
        this.total = response.total
      })
    },
    async handleViewDetail(row) {
      const res = await getActivityDetail(row.id)
      const data = res.data
      console.log('getExamDetail', data)
      const newCurrentActivity = {
        id: data.id,
        title: data.title,
        type: data.type,
        startTime: data.startTime,
        endTime: data.endTime,
        timeLimit: data.timeLimit,
        needIdentity: data.needIdentity,
        paper: {
          totalScore: data.paperTotalScore,
          passScore: data.paperPassScore
        }
      }
      this.currentActivity = newCurrentActivity
      this.detailDialogVisible = true
    },
    handleStartActivity(activity) {
      if (activity.type === 1 && activity.needIdentity) {
        this.currentActivity = JSON.parse(JSON.stringify(activity))
        this.startIdentityVerification()
      } else {
        // this.$router.push({
        //   path: `/exam/group/activity/${activity.id}`,
        //   query: {
        //     type: activity.type
        //   }
        // })
        console.log('handleStartActivity',this.groupId)
        this.$router.push({
          name: 'ExamActivity',
          query: {
            type: activity.type,
            id: activity.id,
            groupId: this.groupId
          }
        })
      }
    },
    startIdentityVerification() {
      this.verifyStep = 1
      this.identityDialogVisible = true
      this.$nextTick(() => {
        this.startCamera()
      })
    },
    async startCamera() {
      try {
        this.stopCamera()
        const constraints = {
          video: {
            width: {ideal: 640},
            height: {ideal: 800},
            facingMode: 'user'
          }
        }
        this.stream = await navigator.mediaDevices.getUserMedia(constraints)
        this.$refs.video.srcObject = this.stream
      } catch (err) {
        console.error('Error accessing camera:', err)
        this.$message.error('无法访问摄像头: ' + err.message)
      }
    },
    stopCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop())
        this.stream = null
      }
    },
    captureImage() {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')

      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      context.drawImage(video, 0, 0, canvas.width, canvas.height)

      this.capturedImage = canvas.toDataURL('image/jpeg')
      this.verifyStep = 2
      this.stopCamera()
    },
    retryCapture() {
      this.verifyStep = 1
      this.$nextTick(() => {
        this.startCamera()
      })
    },
    confirmIdentity() {
      // 模拟验证过程
      this.verifyStep = 3

      // 实际API调用
      // verifyIdentity({
      //   examId: this.currentActivity.id,
      //   image: this.capturedImage
      // }).then(() => {
      //   this.verifyStep = 3
      //   setTimeout(() => {
      //     this.identityDialogVisible = false
      //     this.$router.push(`/student/exam/activity/${this.currentActivity.id}`)
      //   }, 1500)
      // })

      // 模拟API调用后的跳转
      setTimeout(() => {
        this.identityDialogVisible = false
        this.$router.push({
          name: 'ExamActivity',
          query: {
            type: this.currentActivity.type,
            id: this.currentActivity.id,
            groupId: this.groupId
          }
        })
      }, 1500)
    },
    getActivityStatus(activity) {
      if (activity.type === 3) {
        return activity.status // 作业只有发布状态
      }

      if (activity.status === 0) {
        return 0 // 未发布
      }

      const now = new Date()
      const startTime = activity.startTime ? new Date(activity.startTime) : null
      const endTime = activity.endTime ? new Date(activity.endTime) : null

      if (startTime && endTime) {
        if (now < startTime) {
          return 1 // 未开始
        } else if (now >= startTime && now <= endTime) {
          return 2 // 进行中
        } else {
          return 3 // 已结束
        }
      }

      return activity.status
    },
    formatCountdown(startTime) {
      if (!startTime) return '--'

      const now = new Date()
      const start = new Date(startTime)
      if (now >= start) return '00:00:00'

      const diff = start - now
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)

      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    mockLoadExamList() {
      return [
        {
          id: 1,
          title: '期中考试',
          type: 1,
          status: 1,
          startTime: new Date(Date.now() + 3600000), // 1小时后
          endTime: new Date(Date.now() + 7200000), // 2小时后
          timeLimit: 60,
          needIdentity: true,
          paper: {
            totalScore: 100,
            passScore: 60
          }
        },
        {
          id: 2,
          title: '单元测评',
          type: 2,
          status: 2,
          startTime: new Date(Date.now() - 3600000), // 1小时前
          endTime: new Date(Date.now() + 3600000), // 1小时后
          timeLimit: 30,
          needIdentity: false,
          paper: {
            totalScore: 50,
            passScore: 30
          }
        },
        {
          id: 3,
          title: '课后作业',
          type: 3,
          status: 1,
          startTime: null,
          endTime: null,
          timeLimit: null,
          needIdentity: false,
          paper: {
            totalScore: 20,
            passScore: 12
          }
        }
      ]
    }
  },
  filters: {
    activityTypeFilter(type) {
      const map = {1: 'danger', 2: 'warning', 3: 'success'}
      return map[type] || ''
    },
    activityTypeNameFilter(type) {
      const map = {1: '考试', 2: '测评', 3: '作业'}
      return map[type] || ''
    },
    activityStatusFilter(status) {
      const map = {
        0: '未发布',
        1: '未开始',
        2: '进行中',
        3: '已结束'
      }
      return map[status] || ''
    },
    statusTagTypeFilter(status) {
      const map = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return map[status] || ''
    },
    formatDateTime(date) {
      if (!date) return '--'
      return parseTime(date, '{y}-{m}-{d} {h}:{i}')
    }
  }
}
</script>

<style scoped>
.activity-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.activity-title {
  display: flex;
  align-items: center;
}

.activity-title .el-tag {
  margin-right: 10px;
}

.countdown {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.detail-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-row .label {
  width: 100px;
  color: #909399;
  margin-right: 10px;
}

/* 身份验证样式 */
.identity-verify {
  text-align: center;
}

.verify-step {
  padding: 20px;
}

.camera-container {
  position: relative;
  width: 100%;
  max-width: 400px;
  margin: 0 auto 20px;
}

.camera-preview {
  width: 100%;
  border-radius: 4px;
  background: #000;
}

.camera-canvas {
  display: none;
}

.verify-tip {
  color: #909399;
  margin-bottom: 20px;
}

.verify-info {
  text-align: left;
  max-width: 300px;
  margin: 0 auto;
}

.info-row {
  margin-bottom: 15px;
  display: flex;
}

.info-row .label {
  width: 80px;
  color: #909399;
}

.verify-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.verify-actions {
  margin-top: 30px;
}

.verify-success {
  color: #67c23a;
  padding: 20px 0;
}

.verify-success i {
  font-size: 50px;
  margin-bottom: 10px;
}

.verify-success p {
  margin-top: 10px;
}
</style>
